﻿using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.MSBuild.Tools.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace NuGet.MSBuild.Tools
{
    public class ResolveNuGetToolPath : Task
    {
        [Required]
        public string Solution { get; set; }

        [Output]
        public string ToolPath { get; set; }

        public override bool Execute()
        {
            string root = Path.GetDirectoryName(this.Solution);

            string packagesConfig = Path.Combine(root, ".nuget", SpecialFile.Packages);
            if (File.Exists(packagesConfig))
            {
                this.Log.LogMessage(MessageImportance.Low, "Using {0} located at: {1}", SpecialFile.Packages, packagesConfig);

                NuGetPathResolver resolver = new NuGetPathResolver(
                    this.Log, 
                    Path.GetDirectoryName(this.Solution));

                string path = resolver.GetPath(packagesConfig);
                if (!string.IsNullOrEmpty(path) && File.Exists(Path.Combine(path, NuGetTask.TOOL_NAME)))
                {
                    this.ToolPath = path;
                    return true;
                }
            }

            return false;
        }
    }
}
